package com.pudu.mydemo.utils;

/**
 * Created by guiliu on 2016/7/28.
 */

import android.content.Context;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.media.Ringtone;
import android.os.Handler;
import android.widget.SeekBar;

/**
 * Turns a { @link  SeekBar} into a volume control.
 */
public   class  SeekBarVolumizer  implements SeekBar.OnSeekBarChangeListener, Runnable {

    private Context mContext;
    private  Handler mHandler =  new Handler();

    private AudioManager mAudioManager;
    private   int  mStreamType;
    private   int  mOriginalStreamVolume;
    private Ringtone mRingtone;

    private   int  mLastProgress = -1;
    private  SeekBar mSeekBar;


    public  SeekBarVolumizer(Context context, SeekBar seekBar,  int  streamType) {
        mContext = context;
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mStreamType = streamType;
        mSeekBar = seekBar;

        initSeekBar(seekBar);
    }

    private   void  initSeekBar(SeekBar seekBar) {
        seekBar.setMax(mAudioManager.getStreamMaxVolume(mStreamType));
        mOriginalStreamVolume = mAudioManager.getStreamVolume(mStreamType);
        seekBar.setProgress(mOriginalStreamVolume);
        seekBar.setOnSeekBarChangeListener( this );

    }

    public   void  revertVolume() {
        mAudioManager.setStreamVolume(mStreamType, mOriginalStreamVolume, 0);
    }

    public   void  onProgressChanged(SeekBar seekBar,  int  progress,
                                     boolean  fromTouch) {
        if  (!fromTouch) {
            return ;
        }

        postSetVolume(progress);
    }

    void  postSetVolume( int  progress) {
        //  Do the volume changing separately to give responsive UI
        mLastProgress = progress;
        mHandler.removeCallbacks( this );
        mHandler.post( this );
    }

    public   void  onStartTrackingTouch(SeekBar seekBar) {
    }

    public   void  onStopTrackingTouch(SeekBar seekBar) {
    }

    public   void  run() {
        mAudioManager.setStreamVolume(mStreamType, mLastProgress, 0);
    }

    public   void  stopSample() {
        if  (mRingtone !=  null ) {
            mRingtone.stop();
        }
    }

    public SeekBar getSeekBar() {
        return  mSeekBar;
    }

    public   void  changeVolumeBy( int  amount) {
        mSeekBar.incrementProgressBy(amount);
      
        postSetVolume(mSeekBar.getProgress());
    }


}
